<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { User, EditPen, Delete } from '@element-plus/icons-vue';
import {
  addUserToBackend,
  fetchUsers,
  deleteUserFromBackend,
  updateUserToBackend
} from '@/api/user';
import { fetchDepartments } from '@/api/department'
import { ElMessage, ElMessageBox } from 'element-plus';
import { onBeforeRouteLeave } from 'vue-router';

// 响应式数据
const users = ref([]);
const tempForm = ref({
  username: '',
  password: '',
  role: '',
  departmentId: null
});
const dialogVisible = ref(false);
const userTableRef = ref(null);
const selectedUsers = ref([]);
const storedSelectedIds = ref([]);

// 角色选项
const roleOptions = [
  { label: '员工', value: 1 },
  { label: '主管', value: 2 },
];

// 表单数据
const form = ref({
  username: '',
  password: '',
  role: '',
  departmentId: null
});

// 加载选中ID
const loadSelectedIds = () => {
  const saved = localStorage.getItem('selectedUserIds');
  if (saved) {
    storedSelectedIds.value = JSON.parse(saved);
  }
};

// 保存选中ID
const saveSelectedIds = () => {
  localStorage.setItem('selectedUserIds', JSON.stringify(storedSelectedIds.value));
};

// 页面离开时保存状态
onBeforeRouteLeave((to, from, next) => {
  localStorage.setItem('tempForm', JSON.stringify(tempForm.value));
  saveSelectedIds();
  next();
});

// 恢复选中状态
const restoreSelection = () => {
  if (!userTableRef.value || !users.value.length) return;

  userTableRef.value.clearSelection();

  // 选中当前页中已存储的用户
  users.value.forEach(user => {
    if (storedSelectedIds.value.includes(user.id)) {
      userTableRef.value.toggleRowSelection(user, true);
    }
  });

  // 更新当前页选中用户
  selectedUsers.value = users.value.filter(user =>
    storedSelectedIds.value.includes(user.id)
  );
};

// 单选处理
const handleSelect = (selection, row) => {
  const isSelected = selection.some(item => item.id === row.id);

  if (isSelected) {
    if (!storedSelectedIds.value.includes(row.id)) {
      storedSelectedIds.value.push(row.id);
    }
  } else {
    storedSelectedIds.value = storedSelectedIds.value.filter(id => id !== row.id);
  }

  // 更新当前页选中用户
  selectedUsers.value = selection;
  saveSelectedIds();
};

// 全选处理
const handleSelectAll = (selection) => {
  if (selection.length === 0) {
    // 取消全选 - 只移除当前页用户的选中状态
    users.value.forEach(user => {
      storedSelectedIds.value = storedSelectedIds.value.filter(id => id !== user.id);
    });
  } else {
    // 全选 - 添加当前页所有用户的选中状态
    users.value.forEach(user => {
      if (!storedSelectedIds.value.includes(user.id)) {
        storedSelectedIds.value.push(user.id);
      }
    });
  }

  selectedUsers.value = selection;
  saveSelectedIds();
};

// 移除选中用户
const handleRemoveSelected = (user) => {
  // 从存储的选中ID中移除
  storedSelectedIds.value = storedSelectedIds.value.filter(id => id !== user.id);

  // 从显示的选中用户中移除
  selectedUsers.value = selectedUsers.value.filter(u => u.id !== user.id);

  // 如果该用户在当前页，更新表格选中状态
  if (users.value.some(u => u.id === user.id)) {
    userTableRef.value?.toggleRowSelection(user, false);
  }

  saveSelectedIds();
};
// 同步选中状态
const syncSelectionState = () => {
  nextTick(() => {
    if (!userTableRef.value || !users.value.length) return;

    // 获取当前所有选中行
    const currentSelected = userTableRef.value.selection || [];
    const currentSelectedIds = currentSelected.map(u => u.id);

    // 应该选中的ID
    const shouldSelectedIds = storedSelectedIds.value;

    // 同步选中状态
    users.value.forEach(user => {
      const shouldSelect = shouldSelectedIds.includes(user.id);
      const isSelected = currentSelectedIds.includes(user.id);

      if (shouldSelect && !isSelected) {
        userTableRef.value.toggleRowSelection(user, true);
      } else if (!shouldSelect && isSelected) {
        userTableRef.value.toggleRowSelection(user, false);
      }
    });
  });
};

// 编辑用户
const editUser = (user) => {
  form.value = {
    ...user,
    role: user.role === '员工' ? 1 : 2,
    password: '' // 清空密码字段
  };
  dialogVisible.value = true;
};

// 打开添加用户对话框
const openAddDialog = () => {
  form.value = {
    username: tempForm.value.username,
    password: tempForm.value.password,
    role: tempForm.value.role,
    departmentId: tempForm.value.departmentId,
    id: undefined // 确保没有ID
  };
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!form.value.username || !form.value.role || !form.value.departmentId) {
    ElMessage.warning('请填写所有必填字段!');
    return;
  }

  try {
    const submitData = {
      id: form.value.id,
      username: form.value.username,
      password: form.value.password || undefined, // 空密码不传
      role: form.value.role,
      departmentId: form.value.departmentId
    };

    await (form.value.id
      ? updateUserToBackend(submitData)
      : addUserToBackend(submitData));

    ElMessage.success(form.value.id ? "修改用户成功！" : "添加用户成功！");

    // 如果是添加操作，保存表单数据到tempForm
    if (!form.value.id) {
      tempForm.value = {
        username: form.value.username,
        password: form.value.password,
        role: form.value.role,
        departmentId: form.value.departmentId
      };
      tempForm.value = ''
      form.value = ''
    }

    dialogVisible.value = false;
    await getUsers();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error("操作失败");
  }
};

// 对话框关闭时处理
const handleDialogClose = () => {
  // 如果是添加操作且未提交，保存当前表单数据
  if (!form.value.id) {
    tempForm.value = {
      username: form.value.username,
      role: form.value.role,
      departmentId: form.value.departmentId
    };
  }
  // 重置表单
  form.value = { username: '', password: '', role: '', departmentId: null };
};

// 批量删除用户
const batchDeleteUsers = async () => {
  if (!storedSelectedIds.value.length) {
    ElMessage.warning('请先选择要删除的用户');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${storedSelectedIds.value.length} 个用户吗?`,
      '批量删除确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );

    await Promise.all(storedSelectedIds.value.map(id =>
      deleteUserFromBackend(id)
    ));

    storedSelectedIds.value = [];
    selectedUsers.value = [];
    saveSelectedIds();
    ElMessage.success('批量删除成功');
    await getUsers();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 通过ID移除选中用户
const handleRemoveSelectedById = (id) => {
  // 从存储中移除
  storedSelectedIds.value = storedSelectedIds.value.filter(storedId => storedId !== id);

  // 如果用户在当前页，更新表格选中状态
  const userInPage = users.value.find(user => user.id === id);
  if (userInPage) {
    userTableRef.value?.toggleRowSelection(userInPage, false);
    selectedUsers.value = selectedUsers.value.filter(u => u.id !== id);
  }

  saveSelectedIds();
};

// 删除单个用户
const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定删除 ${user.role} ${user.username} 吗?`,
      '删除确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );

    await deleteUserFromBackend(user.id);

    // 1. 从主列表中移除
    users.value = users.value.filter(u => u.id !== user.id);

    // 2. 如果该用户是被选中的，从选中列表中移除
    if (selectedUsers.value.some(u => u.id === user.id)) {
      selectedUsers.value = selectedUsers.value.filter(u => u.id !== user.id);
      storedSelectedIds.value = storedSelectedIds.value.filter(id => id !== user.id);
    }

    // 3. 无论是否选中，都同步表格状态
    nextTick(() => {
      // 确保从表格中移除选中状态
      userTableRef.value?.toggleRowSelection(user, false);

      // 完全同步选中状态
      syncSelectionState();
    });
    getUsers()

    ElMessage.success("用户删除成功！");
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error("用户删除失败！");
    }
  }
};

//部门选项
const departmentOptions = ref([])
// 获取部门列表
// 获取部门列表 - 修改为获取简单列表
const getDepartments = async () => {
  try {
    const response = await fetchDepartments({
      page: 1,
      size: 100
    });

    if (response.data.code === 200) {
      // 修改为简单数组，只包含启用的部门
      departmentOptions.value = response.data.data.departments
        .filter(dept => dept.status === 1) // 只显示启用的部门
        .map(dept => ({
          value: dept.id,
          label: dept.name
        }));
    }
  } catch (error) {
    console.error('获取部门列表失败:', error);
  }
};
// 初始化
onMounted(() => {
  const savedData = localStorage.getItem('tempForm');
  if (savedData) {
    tempForm.value = JSON.parse(savedData);
  }
  loadSelectedIds();
  getUsers();
  getDepartments()
});

// -------------------------------------------搜索功能
const searchForm = ref({
  username: '',
  role: '',
  departmentId: null
});

// 原始用户数据备份
const originalUsers = ref([]);

// 获取所有用户
const getUsers = async () => {
  loading.value = true;
  if (searchForm.value.role === '') {
    searchForm.value.role = null;
  }
  try {
    const response = await fetchUsers({
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      ...searchForm.value
    });

    if (response.data.code === 200) {
      users.value = response.data.data.userBacks;
      pagination.value.total = response.data.data.total;
      // 数据加载完成后恢复选中状态
      nextTick(() => {
        restoreSelection();
      });
    }
  } catch (error) {
    console.error('获取用户失败:', error);
    ElMessage.error('获取用户数据失败');
  } finally {
    loading.value = false;
  }
}
// 搜索方法
const handleSearch = () => {
  pagination.value.currentPage = 1; // 搜索时重置到第一页
  getUsers();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: '',
    role: '',
    departmentId: null
  };
  pagination.value.currentPage = 1;
  getUsers();
};

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const pageSizes = [5, 10, 20, 50, 100];

// 添加分页变化处理
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  pagination.value.currentPage = 1;
  getUsers();
};

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  getUsers();
};

const loading = ref(false);

// 根据ID获取用户对象
const getUserById = (id) => {
  // 先查当前页
  const userInPage = users.value.find(user => user.id === id);
  if (userInPage) return userInPage;

  // 可以扩展这里从其他来源查找用户
  return null;
};

const roleOptions1 = [
  { label: '员工', value: 'employee' },
  { label: '主管', value: 'manager' },
];
</script>

<template>
  <div>
    <h2>用户管理</h2>
    <!-- 搜索方法 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.username" placeholder="请输入姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable style="width: 200px">
            <el-option v-for="item in roleOptions1" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="searchForm.departmentId" placeholder="请选择部门" clearable style="width: 200px">
            <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 一键删除和添加用户 -->
    <div class="action-buttons">
      <el-button type="primary" :icon="User" @click="openAddDialog">
        添加用户
      </el-button>
      <el-button type="danger" :icon="Delete" @click="batchDeleteUsers" :disabled="!storedSelectedIds.length">
        一键删除 ({{ storedSelectedIds.length }})
      </el-button>
    </div>

    <!-- 展示用户 -->
    <div class="user-management">
      <el-table v-loading="loading" :data="users" class="data-table" stripe @select="handleSelect"
        @select-all="handleSelectAll" ref="userTableRef" row-key="id">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag :type="row.role === 'manager' ? 'primary' : 'success'">
              {{ row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="departmentId" label="部门">
          <template #default="{ row }">
            {{row.departmentname || departmentOptions.find(d => d.value === row.departmentId)?.label ||
              row.departmentId}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" :icon="EditPen" circle @click="editUser(row)" />
            <el-button type="danger" :icon="Delete" circle @click="handleDeleteUser(row)" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="pageSizes" :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <div v-if="storedSelectedIds.length" class="selected-info">
        已选择 {{ storedSelectedIds.length }} 个用户:
        <el-tag v-for="id in storedSelectedIds" :key="id" type="info" closable @close="handleRemoveSelectedById(id)">
          {{ getUserById(id)?.username || '未知用户' }}
        </el-tag>
      </div>
    </div>

    <!-- 浮窗窗口 -->
    <el-dialog v-model="dialogVisible" :title="form.id ? '修改用户' : '添加用户'" width="50%" @close="handleDialogClose">
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="部门" required>
          <el-tree-select v-model="form.departmentId" :data="departmentOptions" placeholder="请选择部门" style="width: 100%"
            :props="{ value: 'value', label: 'label', children: 'children' }" />
        </el-form-item> -->
        <el-form-item label="部门" required>
          <el-select v-model="form.departmentId" placeholder="请选择部门" style="width: 100%">
            <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-button type="primary" :icon="form.id ? EditPen : User" @click="handleSubmit">
          {{ form.id ? '确定修改' : '添加用户' }}
        </el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-container {
  padding: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.user-management {
  background: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.data-table {
  width: 100%;
  margin-bottom: 20px;
}

.selected-info {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-info .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>